<template>
  <div class="question-search-view">
    <!-- 搜索头部 -->
    <div class="search-header">
      <div class="search-container">
        <h1 class="page-title">题目搜索</h1>
        <p class="page-subtitle">搜索和浏览各类题目，提升学习效果</p>
        
        <!-- 搜索框 -->
        <div class="search-box">
          <div class="search-input-wrapper">
            <el-input
              v-model="searchKeyword"
              placeholder="输入题目关键词、内容或编号进行搜索..."
              size="large"
              class="search-input"
              @keyup.enter="handleSearch"
              @input="handleInputChange"
              @focus="showSuggestions = true"
              @blur="handleInputBlur"
              clearable
              ref="searchInputRef"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <!-- 搜索记录浮窗 -->
            <div 
              v-if="showSuggestions && searchHistory.length > 0" 
              class="search-suggestions"
            >
              <div class="suggestions-header">
                <span class="suggestions-title">搜索记录</span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="clearSearchHistory"
                  class="clear-btn"
                >
                  清空
                </el-button>
              </div>
              <div 
                v-for="(history, index) in searchHistory" 
                :key="history.id"
                class="suggestion-item"
                :class="{ 'active': selectedSuggestionIndex === index }"
                @click="selectHistory(history)"
                @mouseenter="selectedSuggestionIndex = index"
              >
                <div class="suggestion-content">
                  <div class="suggestion-title">{{ history.keyword }}</div>
                  <div class="suggestion-meta">
                    <span class="suggestion-time">{{ formatTime(history.searchTime) }}</span>
                    <span class="suggestion-count">{{ history.resultCount }} 个结果</span>
                  </div>
                </div>
                <div class="suggestion-action">
                  <el-icon @click.stop="deleteHistory(history.id)"><Close /></el-icon>
                </div>
              </div>
            </div>
          </div>
          
          <el-button 
            type="primary" 
            size="large" 
            @click="handleSearch"
            class="search-btn"
          >
            搜索
          </el-button>
        </div>
        
        <!-- 高级搜索 -->
        <div class="advanced-search" v-show="showAdvanced">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select v-model="searchFilters.category" placeholder="选择分类" clearable>
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="searchFilters.difficulty" placeholder="选择难度" clearable>
                <el-option label="简单" value="1" />
                <el-option label="中等" value="2" />
                <el-option label="困难" value="3" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="searchFilters.type" placeholder="选择类型" clearable>
                <el-option label="单选题" value="single" />
                <el-option label="多选题" value="multiple" />
                <el-option label="判断题" value="judge" />
                <el-option label="填空题" value="fill" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button @click="resetFilters">重置筛选</el-button>
            </el-col>
          </el-row>
        </div>
        
        <!-- 切换高级搜索 -->
        <div class="search-actions">
          <el-button 
            type="text" 
            @click="toggleAdvanced"
            class="toggle-advanced"
          >
            {{ showAdvanced ? '收起' : '展开' }}高级搜索
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results">
      <div class="results-header">
        <div class="results-info">
          <span class="results-count">找到 {{ filteredQuestions.length }} 道题目</span>
          <span class="search-time" v-if="searchTime">用时 {{ searchTime }}ms</span>
        </div>
        <div class="results-actions">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
            <el-option label="按相关度" value="relevance" />
            <el-option label="按难度" value="difficulty" />
            <el-option label="按创建时间" value="createdAt" />
            <el-option label="按答题次数" value="attempts" />
          </el-select>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="questions-list" v-if="!loading">
        <div 
          v-for="question in paginatedQuestions" 
          :key="question.id" 
          class="question-card"
          @click="viewQuestionDetail(question)"
        >
          <div class="question-header">
            <div class="question-meta">
              <el-tag :type="getDifficultyType(question.difficulty)" size="small">
                {{ getDifficultyText(question.difficulty) }}
              </el-tag>
              <el-tag type="info" size="small">{{ question.type }}</el-tag>
              <el-tag v-if="question.category" type="success" size="small">
                {{ question.categoryName }}
              </el-tag>
            </div>
            <div class="question-actions">
              <el-button type="text" size="small" @click.stop="toggleFavorite(question)">
                <el-icon :class="{ 'favorited': question.isFavorite }">
                  <Star />
                </el-icon>
              </el-button>
            </div>
          </div>
          
          <div class="question-content">
            <h3 class="question-title">{{ question.title }}</h3>
            <p class="question-description">{{ question.content }}</p>
            
            <!-- 选项预览 -->
            <div class="question-options" v-if="question.options && question.options.length > 0">
              <div 
                v-for="(option, index) in question.options.slice(0, 2)" 
                :key="index"
                class="option-item"
              >
                <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                <span class="option-text">{{ option }}</span>
              </div>
              <div v-if="question.options.length > 2" class="more-options">
                还有 {{ question.options.length - 2 }} 个选项...
              </div>
            </div>
          </div>
          
          <div class="question-footer">
            <div class="question-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ question.viewCount || 0 }} 次查看
              </span>
              <span class="stat-item">
                <el-icon><EditPen /></el-icon>
                {{ question.attemptCount || 0 }} 次答题
              </span>
              <span class="stat-item">
                <el-icon><Check /></el-icon>
                {{ question.correctRate || 0 }}% 正确率
              </span>
            </div>
            <div class="question-time">
              <el-icon><Clock /></el-icon>
              {{ formatTime(question.createdAt) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredQuestions.length === 0" class="empty-state">
        <el-empty description="没有找到相关题目">
          <el-button type="primary" @click="resetSearch">重新搜索</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredQuestions.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredQuestions.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Star, View, EditPen, Check, Clock, Close } from '@element-plus/icons-vue'
import { searchQuestions, getQuestionCategories } from '@/api/question'
import { saveSearchHistory, getRecentSearchHistory, clearSearchHistory as clearSearchHistoryApi } from '@/api/search-history'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const showAdvanced = ref(false)
const searchTime = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const sortBy = ref('relevance')

// 搜索筛选条件
const searchFilters = ref({
  category: '',
  difficulty: '',
  type: ''
})

// 数据
const questions = ref<any[]>([])
const categories = ref<any[]>([])

// 搜索记录相关
const searchHistory = ref<any[]>([]) // 搜索记录
const showSuggestions = ref(false) // 是否显示搜索记录
const selectedSuggestionIndex = ref(-1) // 当前选中的记录索引
const searchInputRef = ref() // 搜索输入框引用

// 计算属性
const filteredQuestions = computed(() => {
  let filtered = [...questions.value]
  
  // 注意：关键词搜索现在由编辑距离算法处理，不需要额外的过滤
  
  // 分类筛选
  if (searchFilters.value.category) {
    filtered = filtered.filter(question => 
      question.categoryId === searchFilters.value.category
    )
  }
  
  // 难度筛选
  if (searchFilters.value.difficulty) {
    filtered = filtered.filter(question => 
      question.difficulty === parseInt(searchFilters.value.difficulty)
    )
  }
  
  // 类型筛选
  if (searchFilters.value.type) {
    filtered = filtered.filter(question => 
      question.type === searchFilters.value.type
    )
  }
  
  // 排序
  switch (sortBy.value) {
    case 'difficulty':
      filtered.sort((a, b) => a.difficulty - b.difficulty)
      break
    case 'createdAt':
      filtered.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      break
    case 'attempts':
      filtered.sort((a, b) => (b.attemptCount || 0) - (a.attemptCount || 0))
      break
    case 'relevance':
    default:
      // 相关度排序：如果题目有similarity属性，按相似度排序
      filtered.sort((a, b) => {
        if (a.similarity !== undefined && b.similarity !== undefined) {
          return b.similarity - a.similarity
        }
        // 如果没有相似度，按创建时间排序
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      })
      break
  }
  
  return filtered
})

const paginatedQuestions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredQuestions.value.slice(start, end)
})

// 方法
// 加载所有题目（用于编辑距离搜索）
const loadAllQuestions = async () => {
  try {
    console.log('🔄 开始加载所有题目...')
    const response = await searchQuestions({})
    console.log(`✅ 成功加载 ${response.length} 道题目`)
    return response
  } catch (error) {
    console.error('❌ 加载题目失败:', error)
    ElMessage.error('加载题目失败')
    // 使用模拟数据
    const mockQuestions = generateMockQuestions()
    console.log('🔄 使用模拟数据')
    return mockQuestions
  }
}

const loadCategories = async () => {
  try {
    console.log('📂 加载题目分类...')
    const response = await getQuestionCategories()
    categories.value = response
    console.log('✅ 分类加载成功，数量:', response.length)
  } catch (error) {
    console.error('❌ 加载分类失败:', error)
    // 使用默认分类
    categories.value = [
      { id: 1, name: '言语理解与表达' },
      { id: 2, name: '数量关系' },
      { id: 3, name: '判断推理' },
      { id: 4, name: '资料分析' },
      { id: 5, name: '常识判断' }
    ]
    console.log('🔄 使用默认分类')
  }
}


// 编辑距离算法实现
const levenshteinDistance = (str1: string, str2: string): number => {
  const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null))
  
  for (let i = 0; i <= str1.length; i++) matrix[0][i] = i
  for (let j = 0; j <= str2.length; j++) matrix[j][0] = j
  
  for (let j = 1; j <= str2.length; j++) {
    for (let i = 1; i <= str1.length; i++) {
      const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1
      matrix[j][i] = Math.min(
        matrix[j][i - 1] + 1,     // 删除
        matrix[j - 1][i] + 1,     // 插入
        matrix[j - 1][i - 1] + indicator // 替换
      )
    }
  }
  
  return matrix[str2.length][str1.length]
}

// 基于编辑距离的相似度计算（优化版）
const calculateSimilarity = (query: string, text: string): number => {
  if (!query || !text) return 0
  
  const queryLower = query.toLowerCase().trim()
  const textLower = text.toLowerCase().trim()
  
  // 完全匹配
  if (textLower === queryLower) {
    return 1.0
  }
  
  // 开头匹配（权重更高）
  if (textLower.startsWith(queryLower)) {
    return 0.95
  }
  
  // 包含匹配
  if (textLower.includes(queryLower)) {
    return 0.9
  }
  
  // 分词匹配（检查查询词的各个部分是否在文本中）
  const queryWords = queryLower.split(/\s+/).filter(word => word.length > 0)
  if (queryWords.length > 1) {
    const matchedWords = queryWords.filter(word => textLower.includes(word))
    const wordMatchRatio = matchedWords.length / queryWords.length
    if (wordMatchRatio > 0.5) {
      return 0.7 + (wordMatchRatio * 0.2) // 0.7-0.9 之间
    }
  }
  
  // 计算编辑距离相似度
  const distance = levenshteinDistance(queryLower, textLower)
  const maxLength = Math.max(queryLower.length, textLower.length)
  const similarity = 1 - (distance / maxLength)
  
  // 对于短查询，提高相似度阈值
  if (queryLower.length <= 3 && similarity > 0.3) {
    return similarity * 1.2
  }
  
  // 确保相似度不为负数
  return Math.max(0, similarity)
}

// 执行编辑距离搜索
const performLevenshteinSearch = (questions: any[], query: string): any[] => {
  console.log('🔍 开始编辑距离搜索，查询:', query)
  
  const searchResults = questions
    .map(question => {
      // 计算题目内容相似度
      const contentSimilarity = calculateSimilarity(query, question.content || '')
      
      // 计算参考材料相似度
      const materialSimilarity = calculateSimilarity(query, question.referenceMaterial || '')
      
      // 计算分类相似度
      const categorySimilarity = calculateSimilarity(query, question.category?.name || '')
      
      // 计算综合相似度（内容权重最高）
      const totalSimilarity = Math.max(
        contentSimilarity,                    // 内容匹配权重最高
        materialSimilarity * 0.7,            // 参考材料权重0.7
        categorySimilarity * 0.5             // 分类权重0.5
      )
      
      return {
        ...question,
        similarity: totalSimilarity,
        contentSimilarity,
        materialSimilarity,
        categorySimilarity
      }
    })
    .filter(question => question.similarity > 0.1) // 只保留相似度大于10%的结果
    .sort((a, b) => b.similarity - a.similarity) // 按相似度降序排序
  
  console.log(`📊 编辑距离搜索完成，找到 ${searchResults.length} 道相关题目`)
  console.log('🎯 搜索结果相似度分布:', searchResults.map(q => ({
    id: q.id,
    similarity: q.similarity.toFixed(3),
    content: q.content?.substring(0, 30) + '...'
  })))
  
  return searchResults
}

// 处理输入变化 - 显示搜索记录
const handleInputChange = () => {
  console.log('⌨️ 输入变化:', searchKeyword.value)
  
  if (searchKeyword.value.length < 1) {
    showSuggestions.value = false
    return
  }
  
  // 显示搜索记录
  showSuggestions.value = searchHistory.value.length > 0
  selectedSuggestionIndex.value = -1
}

// 处理输入框失焦
const handleInputBlur = () => {
  // 延迟隐藏，让点击事件能够触发
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}

// 选择搜索记录
const selectHistory = (history: any) => {
  console.log('🎯 选择搜索记录:', history)
  searchKeyword.value = history.keyword
  showSuggestions.value = false
  handleSearch()
}

// 删除搜索记录
const deleteHistory = async (historyId: number) => {
  try {
    // 这里可以调用删除单个搜索记录的API
    // 暂时从前端数组中移除
    searchHistory.value = searchHistory.value.filter(h => h.id !== historyId)
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除搜索记录失败:', error)
    ElMessage.error('删除失败')
  }
}

// 清空搜索记录
const clearSearchHistory = async () => {
  try {
    await clearSearchHistoryApi()
    searchHistory.value = []
    showSuggestions.value = false
    ElMessage.success('清空成功')
  } catch (error) {
    console.error('清空搜索记录失败:', error)
    ElMessage.error('清空失败')
  }
}

// 键盘导航
const handleKeydown = (event: KeyboardEvent) => {
  if (!showSuggestions.value || searchHistory.value.length === 0) return
  
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedSuggestionIndex.value = Math.min(
        selectedSuggestionIndex.value + 1,
        searchHistory.value.length - 1
      )
      break
    case 'ArrowUp':
      event.preventDefault()
      selectedSuggestionIndex.value = Math.max(selectedSuggestionIndex.value - 1, -1)
      break
    case 'Enter':
      event.preventDefault()
      if (selectedSuggestionIndex.value >= 0) {
        selectHistory(searchHistory.value[selectedSuggestionIndex.value])
      } else {
        handleSearch()
      }
      break
    case 'Escape':
      showSuggestions.value = false
      break
  }
}

const handleSearch = async () => {
  console.log('🔍 开始搜索，关键词:', searchKeyword.value)
  const startTime = Date.now()
  
  try {
    loading.value = true
    
    // 获取所有题目进行本地编辑距离搜索
    const allQuestions = await loadAllQuestions()
    console.log('📚 获取到所有题目数量:', allQuestions.length)
    
    if (allQuestions.length === 0) {
      questions.value = []
      return
    }
    
    // 如果有关键词，使用编辑距离算法进行模糊搜索
    if (searchKeyword.value && searchKeyword.value.trim()) {
      console.log('🔎 执行编辑距离模糊搜索...')
      const searchResults = performLevenshteinSearch(allQuestions, searchKeyword.value)
      questions.value = searchResults
      console.log(`🎯 编辑距离搜索完成，找到 ${searchResults.length} 道相关题目`)
      
      // 保存搜索记录
      try {
        await saveSearchHistory({
          userId: 1, // 暂时使用固定用户ID
          keyword: searchKeyword.value,
          searchType: 'question',
          resultCount: searchResults.length
        })
        console.log('💾 搜索记录保存成功')
      } catch (error) {
        console.error('保存搜索记录失败:', error)
      }
      
      if (searchResults.length === 0) {
        ElMessage.info('未找到相关题目，请尝试其他关键词')
      }
    } else {
      // 没有关键词时显示所有题目
      questions.value = allQuestions
      console.log('📋 显示所有题目')
    }
  } catch (error) {
    console.error('❌ 搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
    questions.value = []
  } finally {
    loading.value = false
  }
  
  searchTime.value = Date.now() - startTime
  currentPage.value = 1
  console.log(`⏱️ 搜索耗时: ${searchTime.value}ms`)
}

const toggleAdvanced = () => {
  showAdvanced.value = !showAdvanced.value
}

const resetFilters = () => {
  searchFilters.value = {
    category: '',
    difficulty: '',
    type: ''
  }
  handleSearch()
}

const resetSearch = () => {
  searchKeyword.value = ''
  resetFilters()
}

const handleSortChange = () => {
  currentPage.value = 1
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const viewQuestionDetail = (question: any) => {
  router.push(`/question-detail/${question.id}`)
}

const toggleFavorite = (question: any) => {
  question.isFavorite = !question.isFavorite
  ElMessage.success(question.isFavorite ? '已收藏' : '已取消收藏')
}

const getDifficultyType = (difficulty: number) => {
  if (difficulty <= 3) return 'success'
  if (difficulty <= 6) return 'warning'
  return 'danger'
}

const getDifficultyText = (difficulty: number) => {
  if (difficulty <= 3) return '简单'
  if (difficulty <= 6) return '中等'
  return '困难'
}

const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) { // 1天内
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) { // 1周内
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return date.toLocaleDateString()
  }
}

// 加载搜索记录
const loadSearchHistory = async () => {
  try {
    console.log('💾 加载搜索记录...')
    const history = await getRecentSearchHistory()
    searchHistory.value = history || []
    console.log(`✅ 搜索记录加载成功，数量: ${(history || []).length}`)
  } catch (error) {
    console.error('❌ 加载搜索记录失败:', error)
    searchHistory.value = []
  }
}

// 生成模拟数据
const generateMockQuestions = () => {
  const mockQuestions = []
  const types = ['单选题', '多选题', '判断题', '填空题']
  const categories = ['言语理解与表达', '数量关系', '判断推理', '资料分析', '常识判断']
  
  for (let i = 1; i <= 50; i++) {
    mockQuestions.push({
      id: i,
      title: `题目 ${i}`,
      content: `这是第${i}道题目的内容描述，用于测试搜索功能。题目内容包含关键词和相关信息。`,
      type: types[Math.floor(Math.random() * types.length)],
      difficulty: Math.floor(Math.random() * 10) + 1,
      categoryId: Math.floor(Math.random() * 5) + 1,
      categoryName: categories[Math.floor(Math.random() * categories.length)],
      options: ['选项A', '选项B', '选项C', '选项D'],
      viewCount: Math.floor(Math.random() * 1000),
      attemptCount: Math.floor(Math.random() * 500),
      correctRate: Math.floor(Math.random() * 40) + 60,
      isFavorite: false,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    })
  }
  
  return mockQuestions
}

// 监听路由参数
watch(() => route.query, (newQuery) => {
  if (newQuery.category) {
    searchFilters.value.category = newQuery.category as string
  }
  if (newQuery.keyword) {
    searchKeyword.value = newQuery.keyword as string
  }
  if (newQuery.mode === 'practice') {
    // 练习模式
  }
}, { immediate: true })

// 组件挂载
onMounted(() => {
  console.log('🚀 题目搜索页面初始化...')
  
  // 并行加载数据
  Promise.all([
    loadCategories(),
    loadAllQuestions().then(data => {
      questions.value = data
    }),
    loadSearchHistory()
  ]).then(() => {
    console.log('✅ 页面初始化完成')
  }).catch(error => {
    console.error('❌ 页面初始化失败:', error)
  })
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
  console.log('⌨️ 键盘事件监听已添加')
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.question-search-view {
  min-height: 100vh;
  background: #f5f7fa;
}

.search-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 20px;
  color: white;
  
  .search-container {
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
    text-align: center;
  }
  
  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
    text-align: center;
    margin-bottom: 40px;
  }
  
  .search-box {
    display: flex;
    gap: 15px;
    max-width: 800px;
    margin: 0 auto 20px;
    
    .search-input-wrapper {
      position: relative;
      flex: 1;
    }
    
    .search-input {
      width: 100%;
    }
    
    .search-btn {
      padding: 0 30px;
    }
  }
  
  .search-suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    max-height: 300px;
    overflow-y: auto;
    
    .suggestion-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid #f3f4f6;
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover,
      &.active {
        background-color: #f8fafc;
      }
      
      .suggestion-content {
        flex: 1;
        
        .suggestion-title {
          font-size: 14px;
          font-weight: 500;
          color: #1f2937;
          margin-bottom: 4px;
          line-height: 1.4;
        }
        
        .suggestion-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .suggestion-category {
            font-size: 12px;
            color: #6b7280;
          }
        }
      }
      
      .suggestion-score {
        font-size: 12px;
        color: #10b981;
        font-weight: 600;
        min-width: 40px;
        text-align: right;
      }
    }
  }
  
  .advanced-search {
    max-width: 800px;
    margin: 0 auto 20px;
    padding: 20px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    backdrop-filter: blur(10px);
  }
  
  .search-actions {
    text-align: center;
    
    .toggle-advanced {
      color: white;
      font-size: 14px;
    }
  }
}

.search-results {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .results-info {
      .results-count {
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
        margin-right: 20px;
      }
      
      .search-time {
        font-size: 14px;
        color: #6b7280;
      }
    }
  }
  
  .questions-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .question-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
    }
    
    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .question-meta {
        display: flex;
        gap: 8px;
      }
      
      .question-actions {
        .favorited {
          color: #fbbf24;
        }
      }
    }
    
    .question-content {
      margin-bottom: 15px;
      
      .question-title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 10px 0;
      }
      
      .question-description {
        font-size: 14px;
        color: #6b7280;
        line-height: 1.6;
        margin: 0 0 15px 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .question-options {
        .option-item {
          display: flex;
          align-items: center;
          margin-bottom: 5px;
          font-size: 14px;
          color: #6b7280;
          
          .option-label {
            font-weight: 600;
            margin-right: 8px;
            color: #1f2937;
          }
        }
        
        .more-options {
          font-size: 12px;
          color: #9ca3af;
          font-style: italic;
        }
      }
    }
    
    .question-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 15px;
      border-top: 1px solid #e5e7eb;
      
      .question-stats {
        display: flex;
        gap: 20px;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 5px;
          font-size: 12px;
          color: #6b7280;
        }
      }
      
      .question-time {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 12px;
        color: #9ca3af;
      }
    }
  }
  
  .loading-container {
    background: white;
    border-radius: 8px;
    padding: 40px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .empty-state {
    background: white;
    border-radius: 8px;
    padding: 60px 20px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-header {
    padding: 20px 15px;
    
    .page-title {
      font-size: 2rem;
    }
    
    .search-box {
      flex-direction: column;
    }
    
    .advanced-search {
      .el-row {
        .el-col {
          margin-bottom: 10px;
        }
      }
    }
  }
  
  .search-results {
    padding: 15px;
    
    .results-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .question-card {
      .question-footer {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
      }
    }
  }
}
</style>
